import axios from 'axios'
import store from '@/store'
import {Message} from 'element-ui'
import router from "@/router";

const service = axios.create({
  // baseURL: '/yxch/admin',
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
})

// 请求拦截器，成功1，失败2
service.interceptors.request.use((config) => {
  // console.log('request request use:', store.getters.token)
  // 请求成功
  if (store.getters.token) {
    config.headers.Authorization = 'Bearer ' + store.getters.token
  } else {
    console.log('没有token请登录')
  }
  return config
}, (err) => {
  // 请求失败：比如超时
  console.log(err)
  return Promise.reject(err)
})

// 响应拦截器
service.interceptors.response.use((response) => {
// axios默认包含一层data
  const {data, msg, status} = response.data
  if (status) {
    return data
  } else {
    Message.error(msg)
    return Promise.reject(msg)
  }
}, async (err) => {
  console.log(err)
  if (err.code === "A1004" || err.code === "A1001" || err.code === "A1002") {
    // token过期 logout
    Message.warning("登录超时")
    await store.dispatch("user/logout")
    // 主动跳到登录页面
    router.push('/login')
    return Promise.reject(err)
  }
  // 统一处理弹窗
  Message.error(err.message)
  return Promise.reject(err)
})
export default service
